package com.tinyseed.hmxx.admin.security.utils;

import com.tinyseed.hmxx.admin.security.domain.JwtUser;
import com.tinyseed.hmxx.admin.system.domain.dto.UserDTO;
import com.tinyseed.hmxx.admin.system.domain.vo.DeptSmallDTO;
import com.tinyseed.hmxx.admin.system.domain.vo.JobSmallDTO;
import com.tinyseed.hmxx.admin.system.service.JwtPermissionService;
import com.tinyseed.hmxx.admin.system.service.UserService;
import com.tinyseed.hmxx.common.exception.BadRequestException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @version Revision 1.0.0
 * @版权：
 * @author: Howard
 * @email:
 * @see:
 * @创建日期：2020/2/19
 * @功能说明：
 * @begin
 * @修改记录:
 * @修改后版本 修改人        修改内容
 * @2020/2/19 wuxiran        创建
 * @end
 */
@Service("JwtUserDetailsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;
    private final JwtPermissionService permissionService;

    public JwtUserDetailsServiceImpl(UserService userService, UserService userService1, JwtPermissionService permissionService) {
        this.userService = userService1;
        this.permissionService = permissionService;
    }

    /**
     * Description 加载用户信息
     * Version 1.0
     * Date 2020/3/3 12:13 下午
     * Author howard
     *
     * @param
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        UserDTO user = userService.findByName(username);
        if (user == null) {
            throw new BadRequestException("账号不存在");
        } else {
            return createJwtUser(user);
        }
    }

    public UserDetails createJwtUser(UserDTO user) {
        return JwtUser.builder().id(user.getId())
                .username(user.getUsername())
                .password(user.getPassword())
                .avatar(user.getAvatar())
                .createTime(user.getCreateTime())
                .enabled(user.getEnabled())
                .nickName(user.getNickName())
                .lastPasswordResetDate(user.getLastPasswordResetTime())
                .email(user.getEmail())
                .authorities(permissionService.mapToGrantedAuthorities(user))
                .phone(user.getPhone())
                .job(Optional.ofNullable(user.getJob()).map(JobSmallDTO::getName).orElse(null))
                .dept(Optional.ofNullable(user.getDept()).map(DeptSmallDTO::getName).orElse(null))
                .deptId(user.getDeptId())
                .build();
    }

}
